package org.xhy.chameleon.boot;

import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.xhy.beanchameleon.annotation.ChameleonX;
import org.xhy.beanchameleon.core.Chameleon;
import org.xhy.beanchameleon.core.ChameleonSrcCode;
import org.xhy.beanchameleon.pipeline.ChainContext;
import org.xhy.beanchameleon.pipeline.ChainProcess;
import org.xhy.beanchameleon.service.ChameleonManagerService;

/**
 * @description:
 * @gitee: https://gitee.com/XhyQAQ
 * @copyright: B站: https://space.bilibili.com/152686439
 * @Author: Xhy
 * @CreateTime: 2024-03-26 17:11
 */
public class ChameleonSpringFactory extends ChameleonManagerService implements  ChainProcess<ChameleonSrcCode> {

    private DefaultListableBeanFactory beanFactory;

    public ChameleonSpringFactory(DefaultListableBeanFactory beanFactory){
        this.beanFactory = beanFactory;
    }

    @Override
    protected void rem(String chameleonName, String className) {
        beanFactory.destroySingleton(className);
    }

    @Override
    protected void save(String name, String javaSrc, Chameleon chameleon) {
        String beanName = chameleon.getClass().getName();
        if (beanFactory.containsBean(beanName)) {
            remove(null,beanName);
        }
        beanFactory.registerSingleton(beanName,chameleon);
        beanFactory.autowireBean(chameleon);
    }

    @Override
    public void process(ChainContext<ChameleonSrcCode> context) {
        final ChameleonSrcCode processModel = context.getProcessModel();
        final Chameleon chameleon = processModel.getChameleon();
        final String name = chameleon.getClass().getAnnotation(ChameleonX.class).value();
        try {
            super.register(name,processModel.getJavaSrc(),chameleon);
        }catch (BeanDefinitionStoreException e){
            context.setNeedBreak(true);
            context.setException(e);
        }
    }
}
